use std::sync::Arc;
use std::time::Duration;

use futures::SinkExt;
use futures::stream::SplitSink;
use tokio::net::TcpStream;
use tokio::sync::Mutex;
use tokio::time;
use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
use tokio_tungstenite::tungstenite::{Message, Utf8Bytes};

use crate::auth::model::HeartBeat;

pub async fn keep(arc_lock: Arc<Mutex<SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, Message>>>, heartbeat_interval: Option<u64>) {
    loop {
        let send = serde_json::to_string(&HeartBeat::new()).ok().unwrap();
        let mut write = arc_lock.lock().await;
        let result = write.send(Message::Text(Utf8Bytes::from(send))).await;
        match result {
            Ok(_ok) => {
                println!("发送心跳ACK成功！");
            }
            Err(_err) => {
                println!("发送心跳ACK失败！");
                break;
            }
        }
        time::sleep(Duration::from_millis(heartbeat_interval.unwrap())).await;
    }
}